package com.meichis.yndms.vm;

import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.meichis.mcsappframework.executor.MCSExecutorService;
import com.meichis.mcsappframework.executor.MCSRunnable;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.yndms.http.IWebServiceCallback;
import com.meichis.yndms.model.FeedBack;
import com.meichis.yndms.model.Picture;
import com.meichis.yndms.repository.manager.TerminalFeedbackManagert;
import com.meichis.yndms.repository.manager.UploadManager;
import com.meichis.yndms.room.AppDatabase;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TerminalFeedbackDetailVm extends MyViewModel implements IWebServiceCallback {

    private int uploadCount = 0;

    private MutableLiveData<FeedBack> feedBackDetail;

    public List<Picture> piclist = new ArrayList<>();

    private List<String> updImage = new ArrayList<>();

    private MutableLiveData<String> replayContent;

    private MutableLiveData<Boolean> replaySuccess;
    private MutableLiveData<Boolean> finishSuccess;


    private Map<Integer, Picture> mapPics = new android.util.ArrayMap<>();
    private Map<Integer, Picture> mapPicsed = new android.util.ArrayMap<>();

    public MutableLiveData<String> getReplayContent() {
        if (replayContent == null) {
            replayContent = new MutableLiveData<>();
        }
        return replayContent;
    }

    public MutableLiveData<Boolean> getReplaySuccess() {
        if (replaySuccess == null) {
            replaySuccess = new MutableLiveData<>();
            replaySuccess.setValue(false);
        }
        return replaySuccess;
    }

    public MutableLiveData<Boolean> getFinishSuccess() {
        if (finishSuccess == null) {
            finishSuccess = new MutableLiveData<>();
            finishSuccess.setValue(false);
        }
        return finishSuccess;
    }

    public MutableLiveData<FeedBack> getFeedBackDetail() {
        if (feedBackDetail == null) {
            feedBackDetail = new MutableLiveData<>();
        }
        return feedBackDetail;
    }

    public void deleteFeedBackPic() {
        MCSExecutorService.getInstance().execute(new MCSRunnable() {
            @Override
            protected void doBackground() {
                AppDatabase.getInstance().pictureDao().delete(231);
            }

            @Override
            protected void completeOnMain() {

            }
        });
    }

    /**
     * 获取反馈详情
     *
     * @param id 反馈id
     */
    public void GetMyFeedbackByID(int id) {
        TerminalFeedbackManagert.getInstance().GetMyFeedbackByID(getShowDialog(), id, getFeedBackDetail());
    }

    /**
     * 上传附件图片
     */
    public void UploadFeedBackPicture() {
        List<Picture> pictures = AppDatabase.getInstance().pictureDao().find(231, 0, 1);
        if (pictures.size() > 0) {
            UploadPicture(pictures);
        } else {
            SaveFeedBackResult();
        }
    }

    /**
     * 上传附件图片
     */
    private void UploadPicture(List<Picture> pictures) {

        if (pictures == null || pictures.size() == 0) {
            return;
        }

        int sequence = 0;

        for (int i = 0; i < pictures.size(); i++) {
            Picture picture = pictures.get(i);
            sequence = i * 10 + 4;
            mapPics.put(sequence, picture);
            mapPicsed.put(sequence, picture);
            String filepath = picture.getFilePath().startsWith("file:///") ? picture.getFilePath().replace("file:///", "") : picture.getFilePath();
            File file = new File(filepath);
            if (!file.exists()) {
                AppDatabase.getInstance().pictureDao().delete(picture);
                continue;
            }
            picture.setFilePath(filepath);
            UploadManager.getInstance().UploadPicture(getShowDialog(), sequence, picture, this);
        }

    }

    /**
     * 上传回复
     */
    private void SaveFeedBackResult() {

        if (TextUtils.isEmpty(getReplayContent().getValue())) {
            MessageTools.showShortToast("请输入回复内容");
            return;
        }

        StringBuffer sb = new StringBuffer();
        if (updImage != null && updImage.size() > 0) {
            for (int i = 0; i < updImage.size(); i++) {
                if (i < updImage.size() - 1) {
                    sb.append(updImage.get(i) + ",");
                } else {
                    sb.append(updImage.get(i));
                }
            }
        } else {
            sb.append("");
        }

        TerminalFeedbackManagert.getInstance().SaveFeedbackReply(getShowDialog(), getUserInfo().getValue().getOrgId(),
                getUserInfo().getValue().getId(), getFeedBackDetail().getValue().getID(), getReplayContent().getValue(),
                sb.toString(), getReplaySuccess());
    }

    /**
     * 结束反馈
     */
    public void finishFeedBack() {
        TerminalFeedbackManagert.getInstance().SetFeedbackFinish(getShowDialog(), getUserInfo().getValue().getOrgId(),
                getUserInfo().getValue().getId(), getFeedBackDetail().getValue().getID(), getFinishSuccess());
    }

    @Override
    public void onSucceed(int sequence, Object resultPack, String ReturnInfo, int Return) {
        switch (sequence) {
            default:
                if (mapPics.containsKey(sequence)) {
                    updImage.add(mapPics.get(sequence).getGuid());
                    mapPics.remove(sequence);
                    mapPicsed.remove(sequence);
                }
                if (mapPicsed.size() == 0) {
                    if (mapPics.size() == 0) {
                        //没有上传失败的照片，就提交问卷数据
                        SaveFeedBackResult();
                    } else if (uploadCount < 3) {
                        //图片允许失败上传3次
                        uploadCount++;
                        List<Picture> ps = new ArrayList<>();
                        for (Integer i : mapPics.keySet()) {
                            ps.add(mapPics.get(i));
                        }
                        UploadPicture(ps);
                    } else {
                        //3次还是失败，就直接上传数据
                        SaveFeedBackResult();
                    }
                }
        }
    }

    @Override
    public void onFailure(int sequence, int errorCode, String error) {

    }
}
